
import WebSocket from 'ws';
import { SocksProxyAgent } from 'socks-proxy-agent';
import axios from 'axios';
import _ from 'lodash';
import utils from './utils/index.js';
const agent = new SocksProxyAgent(utils.Config.proxy);
const bot = new utils.Notice(utils.Config.bots.okx);
const bigBot = new utils.Notice(utils.Config.bots.okxbig);

(async () => {
  const { data } = await axios.get('https://www.okx.com/api/v5/market/tickers?instType=SWAP', {
    httpAgent: agent,
    httpsAgent: agent,
    timeout: 10000,
  });
  const symbols = data.data
    .map((item) => ({
      channel: "tickers-3s", instId: item.instId
    }));

  const url = 'wss://wspri.okx.com:8443/ws/v5/ipublic';
  var socket = new WebSocket(url, { agent });
  socket.on('open', function open() {
    // 切割 symbols 数组为每个数组最多 200 个元素
    const chunks = _.chunk(symbols, 500);
    chunks.forEach((chunk, i) => {
      socket.send(JSON.stringify( {
        op: 'subscribe',
        args: chunk,
      }));
    });
  });
  socket.on('message', function (data) {
    try {
      const info = JSON.parse(data);
      if (info.data && info.arg && info.arg.channel === 'tickers-3s') {
        let instId = info.data[0].instId.split('-');
        instId = instId[0] + instId[1];
        const symbol = instId + '永续';
        const o = info.data[0].sodUtc0;
        const c = info.data[0].last;
        const rate = (c - o) / o * 100;
        // 张福大于 20% 提醒
        if (rate > 20) {
          bot.add(symbol, `${symbol} ${rate.toFixed(2)}%`);
        } else {
          bot.remove(symbol);
        }
        // 大币策略
        if (_.includes(['BTCUSDT', 'ETHUSDT', 'LTCUSDT', 'BCHUSDT', 'ETCUSDT', 'LINKUSDT', 'YFIUSDT','XRPUSDT'], instId)) {
          if (rate > 5) {
            bigBot.add(symbol, `${symbol} ${rate.toFixed(2)}%`);
          } else {
            bigBot.remove(symbol);
          }
        }
      } else {
        console.log(new Date().toISOString(), ' message type:', info);
      }
    } catch (error) {
      console.error(new Date().toISOString(), 'Error parsing message:', error);
    }
  });
  socket.on('close', function() {
    // 退出
    console.log(new Date().toISOString(), 'WebSocket closed');
    process.exit(0);
  });

  bot.run();
  bigBot.run();
})();


